﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace seiacpscs.sortalgorithms
{
    class SelectionSort : SortAlgorithm
    {
        public SelectionSort()
        {
            this.algorithmName = "Selection Sort";
        }

        public override void Sort(int[] items)
        {
            this.numberOfInnerLoops = 0; // Statistics Code
            this.numberOfOuterLoops = 0; // Statistics Code
            this.numberOfSwaps = 0; // Statistics Code

            int minIndex = 0;
            int innerLoopIndex = 0;
            int outerLoopIndex = 0;

            Stopwatch stopWatch = new Stopwatch(); // Statistics Code
            stopWatch.Start(); // Statistics Code

            for (outerLoopIndex = 0; outerLoopIndex < items.Length - 1; outerLoopIndex++)
            {
                ++(this.numberOfOuterLoops); // Statistics Code
                minIndex = outerLoopIndex;

                for (innerLoopIndex = outerLoopIndex + 1; innerLoopIndex < items.Length; innerLoopIndex++)
                {
                    ++(this.numberOfInnerLoops);
                    if (items[innerLoopIndex] < items[minIndex])
                    {
                        minIndex = innerLoopIndex;
                    }
                }

                //we have to swap the min index
                if (minIndex != outerLoopIndex)
                {
                    ++(this.numberOfSwaps); // Statistics Code
                    int tempValue = items[outerLoopIndex];
                    items[outerLoopIndex] = items[minIndex];
                    items[minIndex] = tempValue;
                }
            }
            stopWatch.Stop(); // Statistics Code
            this.executionTime = (stopWatch.ElapsedTicks * 1000L * 1000L * 1000L) / Stopwatch.Frequency; // Statistics Code
        }
    }
}
